<template>
  <div class="login-container">
    <a-card class="login-card" title="用户登录" :bordered="false">
      <a-form
        :model="form"
        @submit="handleSubmit"
        layout="vertical"
        class="login-form"
      >
        <!-- 用户账号 -->
        <a-form-item label="账号" field="userAccount">
          <a-input
            v-model="form.userAccount"
            placeholder="请输入账号"
            class="custom-input"
          >
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>

        <!-- 用户密码 -->
        <a-form-item
          label="密码"
          field="userPassword"
          tooltip="密码不少于 8 位"
        >
          <a-input-password
            v-model="form.userPassword"
            placeholder="请输入密码"
            class="custom-input"
          >
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>
        <!-- 
        验证码 -->
        <a-form-item label="验证码">
          <div class="captcha-container">
            <a-input
              v-model="yantext"
              placeholder="验证码"
              class="custom-input captcha-input"
            />
            <canvas
              id="canvas"
              width="100"
              height="40"
              class="captcha-canvas"
              @click="draw()"
            ></canvas>
          </div>
        </a-form-item>

        <!-- 记住密码 -->
        <a-form-item>
          <a-checkbox v-model="rememberMe" class="remember-me">
            记住密码
          </a-checkbox>
        </a-form-item>

        <!-- 操作按钮 -->
        <a-form-item>
          <div class="action-buttons">
            <a-button type="primary" html-type="submit" class="submit-btn">
              登录
            </a-button>
            <a-button
              type="outline"
              @click="handleRegister"
              class="register-btn"
            >
              注册
            </a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService, UserLoginRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { onMounted, ref } from "vue";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt.js";
/**
 * 表单信息
 */
const form = reactive({
  userAccount: "",
  userPassword: "",
} as UserLoginRequest);
const rememberMe = ref(false);
const router = useRouter();
const store = useStore();
const handleRegister = () => {
  router.push("/user/register");
};
/**
 * 提交表单
 * @param data
 */
const handleSubmit = async () => {
  // if (yantext.value.length === 0) {
  //   message.warning("请输入验证码");
  //   draw();
  //   return;
  // }
  // if (yantext.value.toUpperCase() !== yanma.value.toUpperCase()) {
  //   message.error("验证码错误");
  //   draw();
  //   return;
  // }

  const res = await UserControllerService.userLoginUsingPost(form);

  if (rememberMe.value) {
    Cookies.set("userAccount", form.userAccount || "", { expires: 30 });
    const encryptedPassword = encrypt(form.userPassword || "") || "";
    Cookies.set("userPassword", encryptedPassword, {
      expires: 30,
    });
    Cookies.set("rememberMe", rememberMe.value.toString(), { expires: 30 });
  } else {
    // 否则移除
    Cookies.remove("userAccount");
    Cookies.remove("userPassword");
    Cookies.remove("rememberMe");
  }
  // 登录成功，跳转到主页
  if (res.code === 0) {
    console.log(res.data);
    store.commit("user/updateToken", res.data);
    await store.dispatch("user/getLoginUser");
    router.push({
      path: "/",
      replace: true,
    });
  } else {
    message.error("登陆失败，" + res.message);
  }
  console.log("存储到store中的token：", store.state.user.token);
};

let yanma = ref<string>("");
let yantext = ref<string>("");

// 验证码图形生成
let show_num: string[] = [];

onMounted(() => {
  getCookie();
  draw();
});

function draw() {
  const canvas = document.getElementById("canvas") as HTMLCanvasElement;
  if (!canvas) return;

  const context = canvas.getContext("2d");
  if (!context) return;

  const canvas_width = canvas.clientWidth;
  const canvas_height = canvas.clientHeight;

  // 清除画布
  context.clearRect(0, 0, canvas_width, canvas_height);

  const sCode =
    "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
  const aCode = sCode.split(",");
  const aLength = aCode.length; // 获取到数组的长度

  for (let i = 0; i <= 3; i++) {
    const j = Math.floor(Math.random() * aLength); // 获取到随机的索引值
    const deg = (Math.random() * 30 * Math.PI) / 180; // 产生0~30之间的随机弧度
    const txt = aCode[j]; // 得到随机的一个字符
    show_num[i] = txt;
    const x = 10 + i * 20; // 文字在canvas上的x坐标
    const y = 20 + Math.random() * 8; // 文字在canvas上的y坐标

    context.font = "23px 微软雅黑";
    context.translate(x, y);
    context.rotate(deg);
    context.fillStyle = randomColor();
    context.fillText(txt, 0, 0);
    context.rotate(-deg);
    context.translate(-x, -y);
  }

  for (let i = 0; i <= 5; i++) {
    context.strokeStyle = randomColor();
    context.beginPath();
    context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
    context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
    context.closePath();
    context.stroke();
  }

  for (let i = 0; i <= 30; i++) {
    context.strokeStyle = randomColor();
    context.beginPath();
    const x = Math.random() * canvas_width;
    const y = Math.random() * canvas_height;
    context.arc(x, y, 1, 0, 2 * Math.PI);
    context.closePath();
    context.stroke();
  }

  yanma.value = show_num.join("");
}

function randomColor(): string {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r},${g},${b})`;
}
function getCookie() {
  const username = Cookies.get("username");
  const password = decrypt(Cookies.get("password") || "");
  const rm = Cookies.get("rememberMe");
  form.userAccount = username;
  form.userPassword = password;
  rememberMe.value = rm === "true";
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.login-card {
  margin-bottom: 150px;
  width: 100%;
  max-width: 480px;
  border-radius: 12px;
  box-shadow: 0 -10px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.login-card:hover {
  transform: translateY(-5px);
}

:deep(.arco-card-header) {
  border-bottom: none;
  padding: 2rem 2rem 1rem;
  font-size: 1.5rem;
  text-align: center;
}

.custom-input {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.custom-input:hover {
  border-color: #3498db;
}

.custom-input:focus-within {
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-canvas {
  border-radius: 8px;
  border: 1px solid var(--color-border);
  cursor: pointer;
  transition: border-color 0.3s;
}

.captcha-canvas:hover {
  border-color: #3498db;
}

.remember-me {
  margin: 12px 0;
  color: #7f8c8d;
}

.action-buttons {
  width: 100%;
  display: flex;
  justify-content: space-between;
  gap: 24px;
}

.submit-btn,
.register-btn {
  flex: 1;
  height: 44px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.submit-btn {
  background: #3498db;
}

.submit-btn:hover {
  background: #2980b9;
  transform: translateY(-1px);
}

.register-btn {
  border-color: #3498db;
  color: #3498db;
}

.register-btn:hover {
  background: rgba(52, 152, 219, 0.1);
  transform: translateY(-1px);
}

:deep(.arco-input-prefix) {
  margin-right: 8px;
  color: #7f8c8d;
}

:deep(.arco-form-item-label) {
  font-weight: 500;
  color: #2c3e50;
}
</style>
